from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from log.models import Log, Comment, Classification, Reply, Member, Contact
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.contrib import auth
from random import choice
import datetime


now = datetime.datetime.now()

def root_directory(request):

    contact_list = Log.objects.order_by('-id')
    classification = Classification.objects.all()
    try:
        images = Contact.objects.get(id=10)
    except:
        images = False

    for j in contact_list:
        j.rep = len(j.comment_set.all())

    for i in classification:
        i.artcle = i.log_set.all()

    paginator = Paginator(contact_list, 5)
    try:
        page = int(request.GET.get('page', 1))
    except ValueError:
        page = 1

    try:
        contacts = paginator.page(page)
    except (EmptyPage, InvalidPage):
        contacts = paginator.page(paginator.num_pages)

    if request.user.is_authenticated():
        judgment = True
    else:
        judgment = False

    return render_to_response('directory.html', {'contacts': contacts, 'images':images,
    'classification': classification, 'judgment': judgment, 'contact_list': contact_list})


def log(request):
    classification = Classification.objects.all()
    if request.POST:
        class_id = request.POST.get('class')
        class_instantiated = Classification.objects.get(id=int(class_id))
        blog = Log(title=request.POST.get('title'),
                   content=request.POST.get('content'),
                   date=now,type=request.POST.get('class'),
                   log_foreign=class_instantiated,
                   label=request.POST.get('label'))
        blog.save()
        return redirect('/')
    return render_to_response('log.html', {'classification': classification})


def log_content(request, a):

    classification = Classification.objects.all()
    for i in classification:
        i.artcle = i.log_set.all()

    try:
        images = Contact.objects.get(id=10)
    except:
        images = False

    contact_list = Log.objects.all()

    l = Log.objects.get(id=a)    
    if request.POST:
        comments = Comment(nickname=request.POST.get('nickname'),
                   porfile = request.POST.get('porfile'),
                   email = request.POST.get('email'),
                   comment = request.POST.get('content'),
                   date = now, log = l, )
        comments.save()
    
    comments = Log.objects.get(id = int(a)).comment_set.all()
 
    for c in comments:
        c.replys = c.reply_set.all() # replys = Comment.objects.get(id=c.id).replu_set.all()

    article = Log.objects.get(id = a)
    adict = {'article': article, 'comments': comments}
    if request.user.is_authenticated():
        judgment = True
    else:
        judgment = False

    return render_to_response('log_content.html', {'adict': adict, 'id': a, 
        'judgment': judgment, 'images': images, 'classification': classification,
        'contact_list': contact_list, 'l': l})


def delete(request, a):
    b = Log.objects.get(id=a)
    b.delete()
    return redirect('/')


def del_comment(request, b):
    comment=Comment.objects.get(id=b)
    comment.delete()
    return redirect('/')


def query(request):
    query_value = request.GET['query']
    query_results = Log.objects.filter(title__contains = query_value)

    if  query_results and request.GET['query']:
        return render_to_response('query_results.html', {'query_results':query_results})
    else:
        return render_to_response('directory.html', {'error': True})


def editor(request, editor_id):
    all = Log.objects.get(id=int(editor_id))
    print 'request.POST:', request.POST

    if request.POST: # request.method == 'GET':
        all.title=request.POST.get('title')
        all.content=request.POST.get('content')
        all.date=now
        all.save()
        return redirect('/')
    
    return render_to_response('editor.html', {'all': all, 'id': editor_id})

def add(request):
    if request.GET:
        add = Classification(type = request.GET['add'])
        add.save()
    
    return redirect('/')

def reply(request, q):
    if request.POST:
        r = Comment.objects.get(id = q)
        reply = Reply(reply_to_comment = request.POST.get('nick'),
                      reply_to_nickname = request.POST.get('con'),
                      date = now, comment_foreign = r)
        reply.save()
        return redirect('/')
    
    return render_to_response('reply.html', {})    

def classification(request, class_id):
    all=Classification.objects.get(id=int(class_id)).log_set.all()
    title = Classification.objects.get(id=int(class_id)).type
    return render_to_response('classification.html', {'all': all, 'title': title})

def login(request):
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            # Correct password, and the user is marked "active"
            auth.login(request, user)
            # Redirect to a success page.
            return HttpResponseRedirect("/")
        else:
            # Show an error page
            render_to_response('login.html')
    return render_to_response('login.html')


def logout(request):
    auth.logout(request)
    # Redirect to a success page.
    return HttpResponseRedirect("/")


def about_me(request):
    return render_to_response('about-me.html')

def upload_pictures(request):
    if request.method == 'POST':
        import StringIO
        from PIL import Image
 
        buf = request.FILES.get('image',None)
        data= buf.read()
        f=StringIO.StringIO(data)
        image=Image.open(f)
        image.thumbnail((250,200), Image.ANTIALIAS)
        image=image.convert('RGB')
        name='static/userpop/'+buf.name 
        image.save(file(name,'wb'),'PNG')
        
        path=buf.name
        a = Contact.objects.get(id=10)
        a.liaison = path
        a.save()
        #people=Contact(liaison=path)
        #people.save()
        return redirect('/')

#    return render_to_response('directory.html')

def delete_images(request):
    a = Contact.objects.get(id=10)
    b = 'static/userpop/'+str(a)
    import os
    os.remove(b)
    #a.delete()
    return redirect('/')

def change_image(request):
    allimage = Contact.objects.get(id=10)
    if request.method == 'POST':
        buf = request.FILES.get('images',None)
        allimage.liaison = buf.name
        allimage.save()
        return redirect('/')